<template>
    <div class="login-container">
        <el-card class="login-card">
            <div class="title">商城管理系统</div>
            <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form"
                @keyup.enter.native="handleLogin">
                <el-form-item prop="username">
                    <el-input v-model="loginForm.username" prefix-icon="el-icon-user" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="loginForm.password" prefix-icon="el-icon-lock" type="password"
                        placeholder="请输入密码" show-password />
                </el-form-item>
                <el-form-item>
                    <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
                </el-form-item>
                <el-form-item>
                    <el-button :loading="loading" type="primary" class="login-button" @click="handleLogin">
                        {{ loading ? '登录中...' : '登录' }}
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
export default {
    name: 'Login',
    data() {
        return {
            loginForm: {
                username: '',
                password: '',
                rememberMe: false
            },
            loginRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                ]
            },
            loading: false,
            redirect: undefined
        }
    },
    created() {
        // 页面创建时从本地存储读取记住的用户名和密码
        this.getRememberedCredentials()
    },
    watch: {
        $route: {
            handler(route) {
                this.redirect = route.query && route.query.redirect
            },
            immediate: true
        }
    },
    methods: {
        handleLogin() {
            this.$refs.loginForm.validate(valid => {
                if (valid) {
                    this.loading = true
                    console.log('表单验证通过，开始登录流程', this.loginForm)

                    // 如果勾选了记住密码，则保存用户名和密码到本地存储
                    if (this.loginForm.rememberMe) {
                        this.saveCredentials()
                    } else {
                        // 如果没有勾选，则清除之前可能保存的凭据
                        this.clearCredentials()
                    }

                    // 添加登录超时处理
                    const loginTimeout = setTimeout(() => {
                        console.warn('登录请求超时')
                        this.loading = false
                        this.$message.error('登录请求超时，请检查网络连接')
                    }, 10000) // 10秒超时

                    // 直接调用API进行测试
                    console.log('尝试直接调用API')
                    import('@/api/user').then(userApi => {
                        console.log('导入userApi成功', userApi)
                        userApi.default.login(this.loginForm)
                            .then(response => {
                                console.log('API直接调用登录成功', response)
                            })
                            .catch(err => {
                                console.error('API直接调用登录失败', err)
                            })
                    }).catch(err => {
                        console.error('导入userApi失败', err)
                    })

                    this.$store
                        .dispatch('user/login', this.loginForm)
                        .then(() => {
                            clearTimeout(loginTimeout)
                            console.log('登录成功，准备跳转')
                            this.$message.success('登录成功')

                            // 给一点延迟，确保token已保存
                            setTimeout(() => {
                                const redirectPath = this.redirect || '/'
                                console.log('跳转到:', redirectPath)
                                this.$router.push({ path: redirectPath })
                            }, 100)
                        })
                        .catch(error => {
                            clearTimeout(loginTimeout)
                            console.error('登录失败:', error)
                            let errorMsg = '登录失败'
                            if (error && error.message) {
                                errorMsg = error.message
                            } else if (typeof error === 'string') {
                                errorMsg = error
                            }
                            this.$message.error(errorMsg)
                        })
                        .finally(() => {
                            this.loading = false
                        })
                } else {
                    console.warn('表单验证失败')
                    return false
                }
            })
        },

        // 保存凭据到本地存储
        saveCredentials() {
            localStorage.setItem('rememberMe', 'true')
            localStorage.setItem('username', this.loginForm.username)
            // 注意：实际项目中不建议直接存储密码，可以考虑加密或其他安全方式
            localStorage.setItem('password', window.btoa(this.loginForm.password)) // 简单的Base64编码
        },

        // 从本地存储读取凭据
        getRememberedCredentials() {
            const rememberMe = localStorage.getItem('rememberMe')
            if (rememberMe === 'true') {
                this.loginForm.rememberMe = true
                this.loginForm.username = localStorage.getItem('username') || ''
                const storedPassword = localStorage.getItem('password')
                if (storedPassword) {
                    // 解码密码
                    this.loginForm.password = window.atob(storedPassword)
                }
            }
        },

        // 清除保存的凭据
        clearCredentials() {
            localStorage.removeItem('rememberMe')
            localStorage.removeItem('username')
            localStorage.removeItem('password')
        }
    }
}
</script>

<style scoped>
.login-container {
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f5f7fa;
}

.login-card {
    width: 400px;
    padding: 20px;
}

.title {
    font-size: 24px;
    font-weight: bold;
    text-align: center;
    margin-bottom: 30px;
    color: #303133;
}

.login-form {
    margin-top: 20px;
}

.login-button {
    width: 100%;
}

.el-input {
    height: 40px;
}

.el-input__inner {
    height: 40px;
    line-height: 40px;
}
</style>